package com.mop.app.controller.anymous;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mop.app.common.BaseController;
import com.mop.app.common.enums.AppBizEnums;
import com.mop.app.controller.vo.LoginUserVO;
import com.mop.app.controller.vo.RegisterUserVO;
import com.mop.app.dal.entity.AppUser;
import com.mop.app.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 用户管理
 *
 * @author wchen
 * @since 2020-02-27
 */
@RestController
@RequestMapping("/anymous/user")
public class AnyUserController extends BaseController {

    public final static String PIC_CODE_KEY = "picCode:%s";
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 用户是否已注册
     *
     * @param appUser
     * @return
     */
    @PostMapping("/isExist")
    public Boolean isExist(@RequestBody AppUser appUser) throws Exception {
        return appUserService.getByPhone(appUser.getPhone()) != null;
    }


    /**
     * 注册用户
     *
     * @param registerUserVO
     * @return
     */
    @PostMapping("/register")
    public String register(@RequestBody RegisterUserVO registerUserVO) throws Exception {
        //校验图形验证码
        String codeKey = String.format(PIC_CODE_KEY, registerUserVO.getPhone());
        Object cacheValue = redisTemplate.opsForValue().get(codeKey);
        AppBizEnums.ERROR_1001.assertTrue(cacheValue != null && cacheValue.toString().equals(registerUserVO.getPicCode()));

        return appUserService.registerUser(registerUserVO);
    }


    /**
     * 登录用户
     *
     * @param loginUserVO
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestBody LoginUserVO loginUserVO) throws Exception {
        return appUserService.loginUser(loginUserVO);
    }


    /**
     * 获取图形验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/picCode/{phoneNo}")
    public void picCode(@PathVariable String phoneNo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        byte[] verByte = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
        String createText = defaultKaptcha.createText();
        redisTemplate.opsForValue().set(String.format(PIC_CODE_KEY, phoneNo), createText);
//        request.getSession().setAttribute("verify_session_Code", createText);
        //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = defaultKaptcha.createImage(createText);
        ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        verByte = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(verByte);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}

